import Immutable from 'immutable';
import moment from 'moment';
import { routerRedux } from 'dva/router';
import {
  queryOilList,
  queryRefuelDetail,
  doRefuel,
  queryRefuelList,
} from '../services/refuel';
// import { inWechat } from '../utils/wechat';
// import toast from '../utils/toast';
import { hideMobile } from '../utils/func';

const OilRecord = Immutable.Record({
  code: null,
  name: null,
}, 'Coupon');

export class Oil extends OilRecord {}

const RefuelRecord = Immutable.Record({
  orderNo: null,
  payTime: null,
  phone: null,
  stationName: null,
  amountYuan: null,
  orderAmountYuan: null, // 加油金额
  orderAmount: null,
  invoiceAmount: null,
  createTime: null,
  disAmountYuan: null, // 优惠金额
  payAmountYuan: null, // 实际支付金额
  gunNo: null,
  oilNo: null,
  selected: false,
});

export class Refuel extends RefuelRecord {
  static parseInvoice(data) {
    return new Refuel({
      ...data,
      stationName: data.oilStation,
      payAmountYuan: data.payFeeYuan,
    });
  }

  static parseOrderList(data) {
    return new Refuel({
      ...data,
    });
  }
  static groupBy(list, key) {
    let orderList = list.groupBy(refuel => moment(refuel.get(key)).format('YYYY年MM月'));
    orderList = Immutable.List(orderList).map((item) => {
      return Immutable.fromJS({
        title: item[0],
        list: item[1],
      });
    });
    return orderList;
  }
  getMobile() {
    return hideMobile(this.get('phone'));
  }
}

export default {
  namespace: 'refuel',
  state: Immutable.fromJS({
    oilList: [],
    refuelDetail: null,
    refuelList: {
      hasMore: false,
      list: [
      ],
      originList: [],
      page: 1,
    },
  }),

  effects: {
    *fetchRefuelList({ payload }, { call, put }) {
      const res = yield call(queryRefuelList, payload);
      if (res.success) {
        yield put({
          type: 'updateRefuelList',
          payload: res.data,
        });
      }
    },
    *refuel({ payload }, { call, put }) {
      const { prePayMode, ...rest } = payload;
      const res = yield call(doRefuel, rest);
      if (res.success) {
        if (res.data.payModeResult === 1) {
          yield put(routerRedux.push(`/${window.source === 'COMMON' ? 'wap' : 'cq'}/result?orderNo=${res.data.orderNo}`));
        } else {
          yield put({
            type: 'pay/prePay',
            payload: {
              type: 'REFUEL',
              payOrderNo: res.data.orderNo,
              orderType: 1,
              payMode: prePayMode,
              callBackUrl: `${window.location.href.split('#')[0]}#/${window.source === 'COMMON' ? 'wap' : 'cq'}/result?orderNo=${res.data.orderNo}`,
            },
          });
        }
      }
    },
    *fetchRefuelDetail({ payload }, { call, put }) {
      const res = yield call(queryRefuelDetail, payload);
      if (res.success) {
        yield put({
          type: 'updateRefuelDetail',
          payload: res.data,
        });
      }
    },
    *fetchOilList({ payload }, { call, put }) {
      const res = yield call(queryOilList, payload);
      if (res.success) {
        yield put({
          type: 'updateOilList',
          payload: res.data,
        });
      }
    },
  },

  reducers: {
    updateRefuelList(state, { payload }) {
      let list = state.getIn(['refuelList', 'originList']);
      if (payload.targetPage === 1) {
        list = list.clear();
      }

      payload.resultList.forEach((item) => {
        list = list.push(Refuel.parseOrderList(item));
      });

      return state.mergeIn(['refuelList'], {
        hasMore: payload.pageCount > payload.targetPage,
        page: payload.targetPage,
        list: Refuel.groupBy(list, 'payTime'),
        originList: list,
      });
    },
    updateRefuelDetail(state, { payload }) {
      return state.set('refuelDetail', new Refuel(payload));
    },
    updateOilList(state, { payload }) {
      const oilList = Immutable.fromJS(payload.map(item => new Oil(item)));
      return state.set('oilList', oilList);
    },
  },
};
